package com.kmproject.haifu.mvp.ui.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.constraint.ConstraintLayout;
import android.support.v7.app.AlertDialog;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.fingerth.supdialogutils.SYSDiaLogUtils;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;

import com.kmproject.haifu.R;
import com.kmproject.haifu.app.utils.ShapeFactoryUtils;
import com.kmproject.haifu.app.utils.StringUtils;
import com.kmproject.haifu.app.utils.TimeUtils;
import com.kmproject.haifu.di.component.DaggerAddUserComponent;

import com.kmproject.haifu.di.module.AddUserModule;
import com.kmproject.haifu.mvp.contract.AddUserContract;
import com.kmproject.haifu.mvp.model.api.Api;
import com.kmproject.haifu.mvp.model.entity.MessageEvent;
import com.kmproject.haifu.mvp.model.entity.User;
import com.kmproject.haifu.mvp.presenter.AddUserPresenter;
import com.kmproject.haifu.mvp.ui.widget.CircleImageView;
import com.kmproject.haifu.mvp.ui.widget.MultiSelectPopWindow;
import com.kmproject.haifu.mvp.ui.widget.SearchEditText;
import com.linchaolong.android.imagepicker.ImagePicker;
import com.linchaolong.android.imagepicker.cropper.CropImage;
import com.linchaolong.android.imagepicker.cropper.CropImageView;
import com.luliang.shapeutils.DevShapeUtils;

import java.util.Arrays;
import java.util.Date;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;



import static com.jess.arms.utils.Preconditions.checkNotNull;


public class AddUserActivity extends BaseActivity<AddUserPresenter> implements AddUserContract.View {

    @BindView(R.id.completeUserInfo_header_img)
    CircleImageView completeUserInfoHeaderImg;
    @BindView(R.id.completeUserInfo_header_lay)
    LinearLayout completeUserInfoHeaderLay;
    @BindView(R.id.setting_userName_SearchEditText)
    SearchEditText settingUserNameSearchEditText;
    @BindView(R.id.setting_phone_lay)
    LinearLayout settingPhoneLay;
    @BindView(R.id.setting_nikeName_SearchEditText)
    SearchEditText settingNikeNameSearchEditText;
    @BindView(R.id.setting_nikeName_lay)
    LinearLayout settingNikeNameLay;
    @BindView(R.id.setting_cell_txt)
    TextView settingCellTxt;
    @BindView(R.id.setting_Property_lay)
    LinearLayout settingPropertyLay;
    @BindView(R.id.setting_Property_txt)
    TextView settingPropertyTxt;
    @BindView(R.id.setting_cell_lay)
    LinearLayout settingCellLay;
    @BindView(R.id.setting_hy_txt)
    TextView settingHyTxt;
    @BindView(R.id.setting_hy_lay)
    LinearLayout settingHyLay;
    @BindView(R.id.setting_gs_SearchEditText)
    SearchEditText settingGsSearchEditText;
    @BindView(R.id.setting_gs_lay)
    LinearLayout settingGsLay;
    @BindView(R.id.completeUserInfo_add_btn)
    Button completeUserInfoAddBtn;
    @BindView(R.id.linearLayout6)
    ConstraintLayout linearLayout6;
    private User muser=null;
    private ImagePicker imagePicker;

    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        DaggerAddUserComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .addUserModule(new AddUserModule(this))
                .build()
                .inject(this);
    }

    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        return R.layout.activity_add_user; //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {

        imagePicker = new ImagePicker();
        imagePicker.setCropImage(true);
        if (getIntent().hasExtra("user"))
        {
//            String url="https://ss0.baidu.com/6ONWsjip0QIZ8tyhnq/it/u=3037936005,3884673282&fm=173&app=25&f=JPEG?w=640&h=590&s=29703A89400EBAF848ED74920300C0C1";

        muser=(User) getIntent().getSerializableExtra("user");
            if (muser.getHeadImg()!=null&&muser.getHeadImg().length()>10)
            {
                Glide.with(this)
                        .load(Api.APP_img+muser.getHeadImg())
                        .into(completeUserInfoHeaderImg);
            }
            settingUserNameSearchEditText.setText(muser.getUsername());
            settingNikeNameSearchEditText.setText(muser.getNikName());
            settingCellTxt.setText(muser.getUserAge()+"");
            settingPropertyTxt.setText(muser.getGender());
            settingHyTxt.setText(muser.getIndustry());
            settingGsSearchEditText.setText(muser.getCompany());


        }else {
            muser=new User("123456");//默认密码123456
        }
        DevShapeUtils.selectorPressed(ShapeFactoryUtils.rectAngleCornor4AndLineColorDrawable(R.color.ehome_selected,R.color.ehome_selected),ShapeFactoryUtils.rectAngleCornor4AndLineColorDrawable(R.color.ehome_selected,R.color.ehome_selected))
            .into(completeUserInfoAddBtn);

    }

    @Override
    public void showLoading() {

        SYSDiaLogUtils.showProgressDialog(this, SYSDiaLogUtils.SYSDiaLogType.IosType, "提交中...", false, new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {

            }
        });
    }

    @Override
    public void hideLoading() {
        SYSDiaLogUtils.dismissProgress();
    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.makeText(this,message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        finish();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @OnClick({R.id.completeUserInfo_header_img,R.id.setting_cell_txt,R.id.setting_Property_txt,R.id.setting_hy_txt,R.id.setting_Property_lay, R.id.setting_cell_lay, R.id.setting_hy_lay, R.id.completeUserInfo_add_btn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.completeUserInfo_header_img:
                selectionImage(completeUserInfoHeaderImg);
                break;
            case R.id.setting_cell_txt:
                //年龄
                new MultiSelectPopWindow.Builder(this)
                        .setConfirmListener(new MultiSelectPopWindow.OnConfirmClickListener() {
                            @Override
                            public void onClick(MessageEvent messageEvent) {
                                settingCellTxt.setText(messageEvent.getSelectData());
                            }
                        })
                        .setDataArray(mPresenter.getAges())
                        .setCancel("取消")
                        .setTitle("请选择年龄")
                        .setConfirm("确定")
                        .build()
                        .show(settingCellTxt);
                break;
            case R.id.setting_Property_txt:
                //性别
                new MultiSelectPopWindow.Builder(this)
                        .setConfirmListener(new MultiSelectPopWindow.OnConfirmClickListener() {
                            @Override
                            public void onClick(MessageEvent messageEvent) {
                                settingPropertyTxt.setText(messageEvent.getSelectData());
                            }
                        })
                        .setDataArray(Arrays.asList(getResources().getStringArray(R.array.sexs)))
                        .setCancel("取消")
                        .setTitle("请选择性别")
                        .setConfirm("确定")
                        .build()
                        .show(settingPropertyTxt);
                break;
            case R.id.setting_hy_txt:
//                Arrays.asList(getResources().getStringArray(R.array.industry))
                new MultiSelectPopWindow.Builder(this)
                        .setConfirmListener(new MultiSelectPopWindow.OnConfirmClickListener() {
                            @Override
                            public void onClick(MessageEvent messageEvent) {
                                settingHyTxt.setText(messageEvent.getSelectData());
                            }
                        })
                        .setDataArray(Arrays.asList(getResources().getStringArray(R.array.industry)))
                        .setCancel("取消")
                        .setTitle("请选择行业")
                        .setConfirm("确定")
                        .build()
                        .show(settingHyTxt);
                break;

            case R.id.completeUserInfo_add_btn:
             if (StringUtils.ViewisEnpty(settingUserNameSearchEditText))
             {
                 ArmsUtils.makeText(this,"请输入用户名");
                 return;
             }
                if (StringUtils.ViewisEnpty(settingNikeNameSearchEditText))
                {
                    ArmsUtils.makeText(this,"请输入昵称");
                    return;
                }
                if (StringUtils.ViewisEnpty(settingCellTxt))
                {
                    ArmsUtils.makeText(this,"请选择年龄");
                    return;
                }
                if (StringUtils.ViewisEnpty(settingPropertyTxt))
                {
                    ArmsUtils.makeText(this,"请选择性别");
                    return;
                }
                if (StringUtils.ViewisEnpty(settingHyTxt))
                {
                    ArmsUtils.makeText(this,"请选择行业");
                    return;
                }
             muser.setUsername(settingUserNameSearchEditText.getText().toString().trim());
             muser.setNikName(settingNikeNameSearchEditText.getText().toString().trim());
             muser.setUserAge(Integer.parseInt(settingCellTxt.getText().toString().trim()));
             muser.setGender(settingPropertyTxt.getText().toString());
             muser.setIndustry(settingHyTxt.getText().toString().trim());
             muser.setCompany(settingGsSearchEditText.getText().toString());
                muser.setRegistTime(TimeUtils.date2String(new Date()));
                mPresenter.addUser(muser);
                break;
        }
    }

    /**
     * 选取图片
     *
     * @param
     */
    public void selectionImage(CircleImageView circleImageView) {
        new AlertDialog.Builder(this).setTitle("选取头像图片")
                .setItems(new String[]{"从相册中选取图片", "拍照"}, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // 回调
                        ImagePicker.Callback callback = new ImagePicker.Callback() {
                            @Override
                            public void onPickImage(Uri imageUri) {

//                                Intent intent = new Intent(UserSettingActivity.this, ClipImageActivity.class);
//                                intent.putExtra("imagePath", imageUri.getEncodedPath());
//                                startActivityForResult(intent, CROPCODE);
//                                imgview.setImageURI(imageUri);
//                                imagePaths[imageIndex] = Utils.getImagePathFromUri(getContext(), imageUri);
                            }

                            @Override
                            public void onCropImage(Uri imageUri) {
//                                userSettingPresent.uploadImg(imgview, imageUri.getEncodedPath());
                                circleImageView.setImageURI(imageUri);
                                mPresenter.updateHeadImg(circleImageView,imageUri.getEncodedPath());
                            }

                            // 自定义裁剪配置
                            @Override
                            public void cropConfig(CropImage.ActivityBuilder builder) {
                                builder
                                        // 是否启动多点触摸
                                        .setMultiTouchEnabled(false)
                                        // 设置网格显示模式
                                        .setGuidelines(CropImageView.Guidelines.OFF)
                                        // 圆形/矩形
                                        .setCropShape(CropImageView.CropShape.OVAL)
                                        // 调整裁剪后的图片最终大小（单位：px）
                                        .setRequestedSize(200, 200)
                                        // 裁剪框宽高比
                                        .setAspectRatio(12, 12);
                            }

                        };
                        if (which == 0) {
                            // 从相册中选取图片
                            imagePicker.startGallery(AddUserActivity.this, callback);
                        } else {
                            // 拍照
                            imagePicker.startCamera(AddUserActivity.this, callback);
                        }
                    }
                })
                .show()
                .getWindow()
                .setGravity(Gravity.BOTTOM);
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        imagePicker.onActivityResult(this, requestCode, resultCode, data);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        imagePicker.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
    }
    @Override
    public void addSuccess(User user) {
      ArmsUtils.makeText(this,"保存成功");
      killMyself();
    }

    @Override
    public void updateHeadSuccess(String headPath) {
      muser.setHeadImg(headPath);
    }
}
